package com.hardydou.system.controller;

import cn.hutool.core.util.StrUtil;
import com.hardydou.common.result.Result;
import com.hardydou.common.controller.BaseController;
import com.hardydou.common.result.ResultAssert;
import com.hardydou.common.result.ResultHelper;
import com.hardydou.framework.log.anno.LogMetaInfo;
import com.hardydou.system.mapper.SystemUserMapper;
import com.hardydou.system.model.LoginUserDetails;
import com.hardydou.system.model.SystemDept;
import com.hardydou.system.service.ISystemDeptService;
import com.hardydou.system.service.ISystemJobService;
import com.hardydou.system.service.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Collections;
import java.util.List;

/**
 * @author ：hardy
 * @description：个人控制器
 * @date ：Created in 2020/6/23
 * @Copyright ：Hardydou.com
 */
@Controller
@RequestMapping("/system")
@LogMetaInfo(module = "个人信息")
public class PersonalController extends BaseController {

    @Autowired
    ISystemUserService systemUserService;
    @Autowired
    ISystemDeptService deptService;
    @Autowired
    ISystemJobService jobService;

    @ApiIgnore
    @GetMapping("/profile")
    public String profile(Model model) {
        LoginUserDetails loginUser = getLoginUserDetails();
        model.addAttribute("user", loginUser.getSystemUser());
        SystemDept dept = deptService.findById(loginUser.getSystemUser().getDeptId());
        String deptName = "";
        if (dept != null) {
            long[] deptIds = StrUtil.splitToLong(dept.getAncestors(), ",");
            List<SystemDept> parents = deptService.findByids(deptIds);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < parents.size(); i++) {
                sb.append(parents.get(i).getDeptName()).append("/");
            }
            sb.append(dept.getDeptName());
            deptName = sb.toString();
        }
        model.addAttribute("deptName", deptName);
        return page("profile");
    }

    @ApiIgnore
    @PutMapping("/avatar.json")
    @ResponseBody
    public Result avatar(String avatar) {
        LoginUserDetails loginUser = getLoginUserDetails();
        loginUser.getSystemUser().setAvatar(avatar);
        systemUserService.update(loginUser.getSystemUser());
        return ResultHelper.ok();
    }

    /***
     * 主模块名称
     * @return
     */
    @Override
    public String getModel() {
        return "sys";
    }

    /***
     * 子模块名称
     * @see #page(String)
     * @return
     */
    @Override
    public String getSubModel() {
        return "user";
    }
}
